package com.lean.android.ad.workflow

import android.app.Activity
import android.os.Process
import com.lean.android.ad.core.PrivacyDialogBlockChain
import com.lean.android.ad.repository.localcache.AdLocalCache
import com.lean.android.ad.utils.AdLog
import kotlin.system.exitProcess

class PrivacyDialogNode(
    private val activity: Activity,
    private val callback: WorkFlows.MainFlowCallback
) : WorkFlowNode {
    override fun enterCondition(): Boolean {
        return !AdLocalCache.isPrivacyAgree && !(activity.isFinishing || activity.isDestroyed)
    }

    override fun enter(workFlow: WorkFlow) {
        if (activity.isFinishing || activity.isDestroyed) {
            AdLog.d(
                AdLog.AdWorkFlowTag, "PrivacyDialogNode enter, but activity is destroyed, skip."
            )
            exit(workFlow)
        } else {
            val chain = object : PrivacyDialogBlockChain {
                override fun onAccept(afterCall: () -> Unit) {
                    AdLocalCache.isPrivacyAgree = true
                    AdLog.d(AdLog.AdWorkFlowTag, "PrivacyDialog onAccept.")
                    afterCall()
                    exit(workFlow)
                }

                override fun onDenied() {
                    Process.killProcess(Process.myPid())
                    exitProcess(0)
                }
            }
            callback.showPrivacyDialog(chain)
            AdLog.d(AdLog.AdWorkFlowTag, "PrivacyDialogNode enter, show privacy dialog.")
        }
    }
}